package org.jfk.tbox.net;

import java.util.HashMap;
import java.util.Map;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

/**
 * 根据tbox协议规则起始符为464C432E，由于没有结束符，半包。
 * @author jxf
 * 2015年8月26日
 */
public class TboxFrameDecoder extends FrameDecoder{
	
	/**
	 * 记录每个channel中的半包，以便和下一个半包进行补齐
	 */
	private static Map halfPkgPool = new HashMap();
	
	private byte[] start = {0x46,0x4C,0x43,0x2E};

	/**
	 *将无头包丢弃
	 *例如：464C432E000069005700EA6ACD8D0000000000010401000101000012000000000000313131313131313131313131313131313131353431353032354C39393039393739313336303055303031303436303033363634313436393937340102030400FF313131313131313131313131313131313150
	 */
	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel,
			ChannelBuffer buffer) throws Exception {
		// TODO Auto-generated method stub
		byte[] a = buffer.array();
		ChannelBuffer frame = ChannelBuffers.buffer(a.length);
		if (a.length > 4 && a[0] == 0x46 && a[1] == 0x4C && a[2] == 0x43 && a[3] == 0x2E){
			frame.writeBytes(a);
			return frame;
		}else{
			System.out.println("无头包，丢弃");
			return null;
		}

	}
}
